#!/usr/bin/bash
#备份参数设置
#mongo容器名称
mongo_container_name=***********
#mongodb的用户名和密码及数据库名称
mongodb_username=******
mongodb_password=******
db_name=******

#设置OSS用户名和密码
MINIO_ROOT_USER=******
MINIO_ROOT_PASSWORD=******
#设置bucket名称
bucket_name=******
#设置备份文件相关
backup_folder=~/backup/data
db_backup_folder_name=db
oss_backup_folder_name=oss
db_backup_folder=$backup_folder/$db_backup_folder_name
oss_backup_folder=$backup_folder/$oss_backup_folder_name

if [ -d $db_backup_folder ];then
	echo "Start restore database"
	echo "开始恢复数据库"
	docker cp $db_backup_folder $mongo_container_name:/tmp
	db_number="$(ls $db_backup_folder | sed -e '/^$/d' | sed -n '$=')"
	echo "You have $db_number collections to restore"
	echo "共有$db_number个集合数据需要恢复"
	i=1
	while [[ $i -le $db_number ]]; do
		collection_file_name="$(ls $db_backup_folder | sed -e '/^$/d' | sed -n "${i}p")"
		collection_name=${collection_file_name%%.*}
		echo "restoring $collection_name"
		docker exec -it $mongo_container_name /opt/bitnami/mongodb/bin/mongoimport -u $mongodb_username -p $mongodb_password -d $db_name -c $collection_name --mode=upsert --type=json --file /tmp/$db_backup_folder_name/$collection_file_name
		let i++
	done
	echo "Restore database successed!"
	echo "数据库恢复成功！"
fi

if [ -d $oss_backup_folder ];then
	echo "Start restore oss files"
	echo "开始恢复OSS文件"
    #默认oss服务器在本机，且端口为9020
	mc alias set ossbackup http://localhost:9020 $MINIO_ROOT_USER $MINIO_ROOT_PASSWORD
	mc mirror --overwrite $oss_backup_folder/ ossbackup/$bucket_name/
fi